package com.cn.qtms.controller;

import com.cn.qtms.common.result.Result;
import com.cn.qtms.common.result.ResultUtil;
import com.cn.qtms.dto.SmsMessage;
import com.cn.qtms.util.StringUtil;
import com.cn.qtms.util.sms.SmsMessageSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @Name:SmsController
 * @Description:
 * @Author: Neil
 * @Date: 2019-08-22 14:28
 **/
@Controller
@RequestMapping("/sms")
public class SmsController {

    @Autowired
    private SmsMessageSender mqSender;

    @Autowired
    private RedisTemplate redisTemplate;



    @RequestMapping(value = "send",method = RequestMethod.GET)
    @ResponseBody
    public Result sendSms(@RequestParam(value = "phone")String phone){

        //先生成一条随机验证码 并发送到MQ中
        String verifyCode =  StringUtil.getVerifyCode();

        mqSender.sendMsg(new SmsMessage(phone,verifyCode));
        //发送完 将验证码存入redis 有效期为5分钟
        redisTemplate.opsForValue().set("verifyCode"+phone,verifyCode,5L, TimeUnit.MINUTES);
        return ResultUtil.success();

    }

    @RequestMapping(value = "verify",method = RequestMethod.POST)
    @ResponseBody
    public Result<String> verifyCode(@RequestBody SmsMessage smsMessage){
        //获取缓存中的验证码
        String checkCodeRedis = (String) redisTemplate.opsForValue().get("verifyCode"+smsMessage.getPhone());
        if (StringUtil.isEmpty(checkCodeRedis)) {
            //从redis中获取的验证码为空,代表没有先获取验证码
            return ResultUtil.error(-1,"请先获取验证码");
        }
        if (!checkCodeRedis.equals(smsMessage.getCode())) {
            //如果输入的验证码不正确,那么也直接返回该方法
            return ResultUtil.error(-1,"请输入正确的验证码");
        }
        return  ResultUtil.success("验证通过");
    }

}
